package com.algorithm.code.queue;

/**
 * @description TODO
 * @program: sudy
 * @author: kukuxiahuni
 * @create: 2020-01-25 18:37
 **/
public class ListQueue<T> implements BaseQueue<T> {

    /**
     * 链表头节点
     */
    private final Node<T> head = new Node<>(null, null);
    private Node<T> tail = head;

    /**
    * @Description: 链表节点
    * @Param:
    * @return:
    * @Author: kukuxiahuni
    * @Date: 2020/1/25
    */
    private final static class Node<T> {
        T value;
        Node<T> next;

        public Node(T value, Node<T> next) {
            this.value = value;
            this.next = next;
        }
    }

    @Override
    public T peek() {

        if (isEmpty()) {
            return null;
        }

        return this.head.next.value;
    }

    @Override
    public T poll() {
        if (isEmpty()) {
            return null;
        }

        Node<T> node = this.head.next;
        this.head.next = node.next;
        return node.value;
    }

    @Override
    public void push(T val) {

        if (val == null) {
            return;
        }
        Node<T> node = new Node<>(val, null);
        tail.next = node;
        tail = node;
    }

    private final void printAll() {

        Node<T> p = this.head.next;

        while (p != null) {
            System.out.println(p.value);
            p = p.next;
        }
    }

    /**
    * @Description: 链表是否为空
    * @Param:
    * @return:
    * @Author: kukuxiahuni
    * @Date: 2020/1/25
    */
    public boolean isEmpty() {
        return head.next == null;
    }

    public static void main(String[] args) {
        ListQueue<Integer> listQueue = new ListQueue<>();

        for (int i = 0; i < 20; ++i) {
            listQueue.push(i);

        }

        listQueue.printAll();
        System.out.println("*******************");
        listQueue.poll();
        listQueue.printAll();
        System.out.println("*******************");
        System.out.println(listQueue.peek());
        System.out.println("*******************");
        listQueue.printAll();
    }
}
